package service

import (
	"context"
	"database/sql"
	"fx_swift_agent/api"
	"fx_swift_agent/pkg/code"
	"fx_swift_agent/pkg/global"
	"fx_swift_agent/pkg/internalerrors"
	"fx_swift_agent/pkg/logger"
)

type INotifySrv interface {
	EditNotify(ctx context.Context, id []string, status string) error

	NotifyHistoryList(ctx context.Context) ([]*api.NotifyHistoryListRes, error)
}
type notifySrv struct {
}

func NewNotifySrv() INotifySrv {
	return &notifySrv{}
}

// 通知列表
func (n *notifySrv) NotifyHistoryList(ctx context.Context) ([]*api.NotifyHistoryListRes, error) {
	var (
		err     error
		account string
		result  = make([]*api.NotifyHistoryListRes, 0)
	)
	account = ctx.Value("Account").(string)
	if err = global.GFDB.Ctx(ctx).Model("fx_notify").
		Where("account=?", account).Order("created_at desc").
		Scan(&result); err != nil {
		logger.SugarLogger.Error(err)
		return nil, internalerrors.New(code.ErrUnknown, "数据库查询失败")
	}
	return result, err
}

// 修改通知状态
func (n *notifySrv) EditNotify(ctx context.Context, id []string, status string) error {
	var (
		err      error
		result   sql.Result
		rowsNums int64
	)
	result, err = global.GFDB.Ctx(ctx).Model("fx_notify").
		Data("status", status).
		Where("id IN(?)", id).Update()
	if err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, "数据库更新失败")
	}
	rowsNums, err = result.RowsAffected()
	if rowsNums == 0 || err != nil {
		logger.SugarLogger.Info(rowsNums)
		return internalerrors.New(code.ErrUnknown, "更新状态失败")
	}
	return err
}
